#include"kernel/types.h"
#include"kernel/fcntl.h"
#include"user/user.h"
#define MAXPRIME 35
#define MINFACTOR 2
int main(){
	int temp;
	int fpid=0;
	int pipe_=0;
	int i,primeCandidate=1;
	int readResult=0;
	int fd[2];
	pipe_=pipe(fd);
	printf("pipe>>%d\n",pipe_);
	fpid=fork();
	if(0){
		printf("pipe error!\n");
		exit(1);
	};
	if(fpid<0){
		printf("fork error!\n");
		exit(1);
	}
	else {
		while(fpid==0){
			sleep(5);
			printf("\n\nWaiting to read...\n");
			readResult=read(fd[0],(void*)&primeCandidate,1);
			printf("ReadResult>>%d\n",readResult);
			printf("number got:%d\n",primeCandidate);
			while(1){
				primeCandidate++;
				if(primeCandidate>=MAXPRIME)
					exit(0);
				else;
				
				for(i=MINFACTOR;i<=primeCandidate;i++){
					if(primeCandidate%i==0){
						printf("found a factor\n");
						break;
					}
					else;
				}
				if(i!=primeCandidate)
					printf("%d is not a prime\n",primeCandidate);				
				else
					break;			
			}
        		printf("found a prime :");
        		printf("%d",primeCandidate);
        		printf("\n");
        		if(primeCandidate==MAXPRIME)
        			exit(0);
        		else{
        			printf("Creating a child process");
        			read(0,(void*)&temp,1);
        			printf("\n");
        			fpid=fork();
        		}
        			
		}
		printf("copying data...\n");
		write(fd[1],(void*)&primeCandidate,1);
		printf("copied\n");
		close(fd[1]);
		printf("pipe closed");
		while(wait(0)!=fpid);
		printf("Child process exited\n");
		printf("Exit: Prime %d\n\n",primeCandidate);
		exit(0);
	}
}
